﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FinalPointSet.Model.Constant;
using FinalPointSet.Model.Constant.Message;
using FinalPointSet.Model.Constants;
using FinalPointSet.Model.Manager;
using FinalPointSet.Model.Model.Knowledge;
using FinalPointSet.Model.Util;
using ICSharpCode.AvalonEdit.Highlighting;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using static FinalPointSet.Model.Manager.MessageManager;
namespace FinalPointSet.ViewModel.Page.MainView
{
    public partial class KnowledgePageViewModel : ObservableObject, IDisposable
    {
        /// <summary>
        /// 原始数据
        /// </summary>
        [ObservableProperty]
        private ObservableCollection<KnowledgePoint> _originalKnowledges = [];
        /// <summary>
        /// 匹配的数据
        /// </summary>
        [ObservableProperty]
        private ObservableCollection<KnowledgePoint> _filterKnowledges = [];
        /// <summary>
        /// 代码框内容
        /// </summary>
        [ObservableProperty]
        private string _content = string.Empty;
        /// <summary>
        /// 当前选中的元素
        /// </summary>
        [ObservableProperty]
        private KnowledgePoint? _selectedKnowledge;
        /// <summary>
        /// 语言列表
        /// </summary>
        [ObservableProperty]
        private List<Language> _Languages = [];
        /// <summary>
        /// 搜索的文字
        /// </summary>
        [ObservableProperty]
        private string _searchWord = string.Empty;
        /// <summary>
        /// 关键词匹配权重
        /// </summary>
        private KeywordMatchWorth? KeywordMatchWorth;
        /// <summary>
        /// 高亮样式
        /// </summary>
        [ObservableProperty]
        private IHighlightingDefinition? _highlightingDefinition;
        public KnowledgePageViewModel()
        {
            InitResource();

            //监听数据源集合资源变化
            AssetManager.Instance.OnJsonObjectListUpdate += OnResourceUpdate;
        }

        private void InitResource(bool isFirst = true)
        {
            //加载知识点数据
            List<KnowledgePoint> listKnow;
            if (!isFirst)
            {
                //不是第一次加载,则说明是语言变动, 需要重新初始化一次知识点
                List<Language> langs = AssetManager.Instance.GetJsonObjectList<Language>();
                AssetManager.Instance.ReloadJsonObjectList<KnowledgePoint>(new KnowledgePointConverter(langs));
            }

            listKnow = AssetManager.Instance.GetJsonObjectList<KnowledgePoint>();
            if (listKnow != null)
            {
                OriginalKnowledges = new ObservableCollection<KnowledgePoint>(listKnow);
                FilterKnowledges = OriginalKnowledges;
            }
            //加载语言
            Languages = AssetManager.Instance.GetJsonObjectList<Language>();
            //加载关键词匹配权重
            KeywordMatchWorth = AssetManager.Instance.GetJsonObject<KeywordMatchWorth>();
            //设置代码高亮
            HighlightingDefinition = AssetManager.Instance.GetObject<IHighlightingDefinition>();
        }

        private void OnResourceUpdate(Type type)
        {
            if (type == typeof(Language))
                InitResource(false);
        }
        /// <summary>
        /// 添加数据
        /// </summary>
        [RelayCommand]
        private void Add()
        {
            int maxID = OriginalKnowledges.Max(e => e.ID);
            Language language = Languages.FirstOrDefault(lang => "Hive".Equals(lang.Name), new());
            KnowledgePoint knowledgePoint = new()
            {
                ID = maxID + 1,
                Language = Language.Clone(language),
                Name = $"知识点{OriginalKnowledges.Count + 1}"
            };
            OriginalKnowledges.Add(knowledgePoint);
            Broadcast(MsgType.GrowMsg, new GrowMsgArg(WindowType.MainView, GrowlMsgType.Success, $"新增知识点[{knowledgePoint.Name}]成功!"));
            Debug.Print($"KeywordPageViewModel.Add(), 新增知识点[{knowledgePoint.Name}]成功!");
        }

        /// <summary>
        /// 保存
        /// </summary>
        [RelayCommand]
        private void Save()
        {
            if (OriginalKnowledges == null)
            {
                Debug.Print("KeywordPageViewModel.Save(),知识点数据为空");
                return;
            }
            List<KnowledgePoint> knowledges = [.. OriginalKnowledges];
            if (knowledges != null)
            {
                AssetManager.Instance.UpdateJsonObjectList(OriginalKnowledges.ToList());
                AssetManager.Instance.SaveJsonObjectList<KnowledgePoint>(new KnowledgePointConverter());
                Broadcast(MsgType.GrowMsg, new GrowMsgArg(WindowType.MainView, GrowlMsgType.Success, $"保存{knowledges.Count}条数据成功!"));
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="knowledge"></param>
        [RelayCommand]
        private void Delete(KnowledgePoint knowledge)
        {
            if (knowledge == null || OriginalKnowledges == null)
                return;
            Debug.Print($"KeywordPageViewModel.Delete(),删除知识点{knowledge}成功!");
            Broadcast(MsgType.GrowMsg, new GrowMsgArg(WindowType.MainView, GrowlMsgType.Success, $"删除知识点[{knowledge.Name}]成功!"));
            //删除源数据和匹配的数据
            OriginalKnowledges.Remove(knowledge);
            FilterKnowledges.Remove(knowledge);
        }

        /// <summary>
        /// 搜索
        /// </summary>
        [RelayCommand]
        private void Search()
        {
            Debug.Print($"KeywordPageViewModel.Search(),当前查询关键词:{SearchWord}");
            if (OriginalKnowledges == null) return;

            //先从上一次的搜索匹配的数据中,更新最新的数据到原始数据中
            var OriginalKnowledgesList = OriginalKnowledges.ToList();
            var FilterKnowledgesList = FilterKnowledges.ToList();
            var UnionList = OriginalKnowledgesList.UnionBy(FilterKnowledgesList, (k => k.ID)).ToList();
            OriginalKnowledges = new ObservableCollection<KnowledgePoint>(OriginalKnowledgesList);

            //匹配搜索命中的数据
            var searchResults = KnowledgePointHelper.GetMatchKnowledgePoints(UnionList, KeywordMatchWorth, SearchWord);
            if (searchResults == null)
                return;
            FilterKnowledges = new ObservableCollection<KnowledgePoint>(searchResults);
        }

        /// <summary>
        /// 设置
        /// </summary>
        [RelayCommand]
        private static void Setting()
        {
            Debug.Print("KeywordPageViewModel.Setting()");
            PageUtil.Instance.Navigate(PageUtil.KnowledgeSettingPage);
        }

        public void OnComboboxSelectionChange(int id, Language? newLanguage, Language? oldLanguage)
        {
            if (newLanguage == null || oldLanguage == null || id <= 0)
                return;
            Debug.Print($"KnowledgePointViewModel.OnComboboxSelectionChange(), 元素ID={id},newLanguage={newLanguage.Name}, oldLanguage={oldLanguage.Name}");
            KnowledgePoint? filterKP = FilterKnowledges.FirstOrDefault(e => e.ID == id);
            KnowledgePoint? originalKP = OriginalKnowledges.FirstOrDefault(e => e.ID == id);
            if (filterKP == null || originalKP == null)
                return;
            Language nLang = Language.Clone(newLanguage);
            filterKP.Language = nLang;
            originalKP.Language = nLang;
            if (SelectedKnowledge != null)
            {
                SelectedKnowledge = KnowledgePoint.Clone(filterKP);
            }
        }

        public void Dispose()
        {
            AssetManager.Instance.OnJsonObjectListUpdate -= OnResourceUpdate;
        }
    }
}
